<?php
if(!defined('IN_SING')) {
	exit('Access Denied');
}
class dbt_trigger extends sing_table{
	
	static $triggers;
	
	public function run(){
            $cdb = DB::object();
		$db = & $cdb;
		$db->triggerIsRun = true;
		$tableArr = $db->tableArr;
		if(count($tableArr) == 0) return;
		foreach($tableArr as $k=>$v){
			foreach($v as $t=>$_v){
				unset($db->tableArr[$k][$t]);
				self::trigger($k, $_v);
			}
			unset($db->tableArr[$k]);		
		}
		$db->triggerIsRun = false;
		if(count($db->tableArr) > 0) self::run();
	}
	
	private function trigger($table,$array){
		//var_dump($array);
		$r = DB::fetch_all('select `type`,`url`,`field`,`value` from %t where display=1 and module=%s', array('trigger', $table));
		foreach($r as $k=>$v){
			switch($v['type']){
				case '1':
					break;
				case '2':
					break;
				case '3':
					break;
				case '4':
					self::loadtrigger($table, $v['field'])->Greater($v['value'] ,$array);
					break;
				case '5':
					self::loadtrigger($table, $v['field'])->Smaller($v['value'] ,$array);
					break;
				case '6':
					break;
				case '7':
					break;
				case '8':
					self::loadtrigger($table, $v['field'])->NotNull($v['value'] ,$array);
					break;
				case '9':
					break;
				case '10':
					break;
				case '11':
					break;									
			}
		}		
	}
	
	private function loadtrigger($t, $f){		
		$cname = $t.'_'.$f;
		list($tt) = explode('_',$t);
		if(!isset(self::$triggers[$cname])) {
			if(!class_exists($cname, false)) {
				//exit(MODULE.'/'.$t.'/trigger/'.$cname);
				if(is_file(MODULE.'/'.$t.'/trigger/'.$cname.'.php')){
					C::import(MODULE.'/'.$t.'/trigger/'.$cname);
				}elseif(is_file(MODULE.'/'.$tt.'/trigger/'.$cname.'.php')){
					C::import(MODULE.'/'.$tt.'/trigger/'.$cname);
				}else{
					
				}
			}
			self::$triggers[$cname] = new $cname();
		}
		return self::$triggers[$cname];
	}
}